//
//  BubbleViewModel.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/7/24.
//

import Foundation
import LeanCloud
class BubbleViewModel: BaseViewModel {
    @Published var items = [BubbleMallBean]()
    @Published var status = ""
    @Published var id = ""

    
    func getData(_ isRefresh: Bool = false) {
        requestList(isRefresh: isRefresh) {
            let versiton = String(getAppVersionAndBuild().version.stringValue.formatVersion())
            let query = LCQuery(className: "BubbleMall")
            query.whereKey("hide", .notEqualTo(true))
            //version_ios 要<= 当前版本号
            query.whereKey("version_ios", .lessThanOrEqualTo(Int(versiton) ?? 0)) //判断版本号
            query.whereKey("sort", .ascending) //升序
            let list =  try await LeancloudManager.instance.getList(query: query, modeType: BubbleMallBean.self)
            try check(!isRefresh || !list.isEmpty, "暂无数据")
            return list
        } suc: { lits in
            if isRefresh {
                self.id = lits[0].id ?? ""
            }
            self.status = ""
            self.items.append(contentsOf: lits)
        } fail: {
            self.status = $0.message
        }
    }
    
    func doChoose(id: String) {
        self.id = ""
        request(isLoading: false) {
            try await Task.sleep(nanoseconds: 300)
            return true
        } suc: { _ in
            self.id = id
        } fail: { _ in
           
        }
    }
    
    func checkExit(id:String, suc: @escaping () -> Void) {
        request {
            try check(userManager.isLogin(), "请先登陆")
            //查询是否已经存在了，避免重复添加
            let query = LCQuery(className: "BubbleMallData")
            query.whereKey("id", .equalTo(id))
            query.whereKey("userId", .equalTo(userManager.getUserId()))
            let bean = try await LeancloudManager.instance.getFirst(query: query, modeType: BubbleMallDataBean.self)
            try check(bean == nil, "已经存在了，无法重复购买")
            return true
        } suc: { _ in
            suc()
        } fail: {
            showToast($0.message)
        }
        
    }
    
    func getPay(bean: BubbleMallBean) {
        //获取购买方式，并且提交预览数据，用于后台查看
        request(isLoading: false) {
            //预览数据
            try await retry(maxRetries: 5, retryDelayMillis: 200) {
                var record = VipPrePayRecordBean()
                record.userId = userManager.getUserId()
                record.userName = userManager.getName()
                record.channel = "apple"
                record.json = toJson(bean)
                try await LeancloudManager.instance.save(todo: record)
            }
            return ""
        } suc: { _ in
            
        } fail: {_ in
        }
    }
    
    func doCreate(bean: BubbleMallBean, deduct: Bool = false) {
        
        request {
            try check(userManager.isLogin(), "请先登陆")
            //开始添加
            let data = BubbleMallDataBean()
            data.mallId = bean.objectId
            data.id = bean.id
            data.userId = userManager.getUserId()
            data.bean = bean
            try await  retry(maxRetries: 5, retryDelayMillis: 500) {
                try await LeancloudManager.instance.save(todo: data)
            }
            //更新BubbleMallBean
            try await retry(maxRetries: 5, retryDelayMillis: 500) {
                bean.count = (bean.count ?? 0) + 1
                try await LeancloudManager.instance.save(todo: bean)
            }
            //扣除次数
            if (deduct) {
                var bubbleCount = userManager.getExtraConfig().bubbleCount ?? 0
                bubbleCount -= bean.bubbleCount ?? 1
                userManager.getExtraConfig().bubbleCount = bubbleCount
                try await retry(maxRetries: 5, retryDelayMillis: 500) {
                    if let user = userManager.user {
                        try await LeancloudManager.instance.save(todo: user)
                        userManager.update()
                    }
                }
            }
            return true
        } suc: { _ in
            showToast("购买成功")
            NotificationCenter.default.post(name: .buyVoice, object: true)
        } fail: {_ in
            showToast("购买失败")
        }
        
    }
}
